package com.xhwl.centiotdata.suppliersystem.vehicle.haikang;

import com.alibaba.fastjson.JSON;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.xhwl.common.dto.cent.vehicle.http.haikang.ResponseAccessRecordHaiKangDTO;
import com.xhwl.common.dto.cent.vehicle.http.haikang.ResponseCommonHaiKangDTO;
import com.xhwl.common.dto.cent.vehicle.http.haikang.query.QueryAccessRecordHaiKangDTO;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.vehicle.bo.config.VehicleParkingInfoBO;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class HaiKangHandler {

    private synchronized void setHaiKangHttpConfig(VehicleParkingInfoBO vehicleParkingInfoBO) {
        ArtemisConfig.host = vehicleParkingInfoBO.getHost();
        ArtemisConfig.appKey = vehicleParkingInfoBO.getAppId();
        ArtemisConfig.appSecret = vehicleParkingInfoBO.getAppSecret();
    }

    private void haiKangResponseHandle(ResponseCommonHaiKangDTO responseCommonHaiKangDTO) {
        if (!"0".equals(responseCommonHaiKangDTO.getCode())) {
            throw new BusinessException("访问海康的http接口，返回的code不是代表成功的0");
        }
    }

    public ResponseAccessRecordHaiKangDTO queryAccessRecord(VehicleParkingInfoBO vehicleParkingInfoBO, QueryAccessRecordHaiKangDTO queryAccessRecordHaiKangDTO) {
        setHaiKangHttpConfig(vehicleParkingInfoBO);

        System.out.println("http hai kang getCrossRecords!");

        final String pathRoot = "/artemis";
        String url = "/api/pms/v1/crossRecords/page";

        Map<String, String> path = new HashMap<>();
        path.put("https://", pathRoot+url);

        String contentType = "application/json";

        String body = JSON.toJSONString(queryAccessRecordHaiKangDTO);
//        System.out.println("body string: " + body);

        String responseString = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);
//        System.out.println("responseString: " + responseString);

        ResponseCommonHaiKangDTO responseCommonHaiKangDTO = JSON.parseObject(responseString, ResponseCommonHaiKangDTO.class);
        haiKangResponseHandle(responseCommonHaiKangDTO);
//        System.out.println("responseCommonHaiKangDTO: " + responseCommonHaiKangDTO);

        return JSON.parseObject(responseCommonHaiKangDTO.getData(), ResponseAccessRecordHaiKangDTO.class);
    }

}
